package com.godyao.mall.oauth.server.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.godyao.mall.core.model.ResultMsg;
import com.godyao.mall.core.model.oauth.OAuthConstant;
import com.godyao.mall.oauth.server.model.SecurityUser;
import com.godyao.mall.user.api.feign.UserFeign;
import com.godyao.mall.user.common.model.SysRole;
import com.godyao.mall.user.common.model.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author godyao
 * @date 2022/4/1
 */
@Service(value = "jwtTokenUserDetailsService")
public class JwtTokenUserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserFeign userFeign;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        final ResultMsg<SysUser> sysUserResult = userFeign.getByUsername(username);
        final SysUser user = sysUserResult.getData();
        if (!ResultMsg.isSuccess(sysUserResult)|| Objects.isNull(sysUserResult.getData())){
            throw new UsernameNotFoundException("用户不存在！");
        }
        //获取当前用户的角色
        ResultMsg<List<SysRole>> roleResult = userFeign.getRolesByUserId(user.getId());
        if (!ResultMsg.isSuccess(roleResult)||Objects.isNull(roleResult.getData())){
            throw new UsernameNotFoundException("获取角色失败！");
        }

        final List<String> roles = roleResult.getData().stream().map(sysRole -> OAuthConstant.ROLE_PREFIX + sysRole.getCode()).collect(Collectors.toList());
        return SecurityUser.builder()
                .nickname(user.getNickname())
                .gender(user.getGender())
                .avatar(user.getAvatar())
                .mobile(user.getMobile())
                .email(user.getEmail())
                .userId(user.getUserId())
                .username(username)
                .password(user.getPassword())
                .authorities(AuthorityUtils.createAuthorityList(ArrayUtil.toArray(roles, String.class)))
                .build();
    }
}
